package com.st.mq.produce_confirm;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author shent
 */
@Configuration
public class RabbitConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);

        rabbitTemplate.setMandatory(true);
        //消息到交换机
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                String msg = String.format("消息送达交换器后消费者没有确认，返回的消息为[%s], 返回的错误提示为[%s]",
                        correlationData != null ? correlationData.getReturned() : "",
                        cause != null ? cause : "");
                System.out.println(msg);
            }
//            System.out.println("ConfirmCallback:相关数据: " + correlationData);
//            System.out.println("ConfirmCallback:确认情况: " + ack);
//            System.out.println("ConfirmCallback:原因: " + cause);
        });
        //消息到队列
        rabbitTemplate.setReturnsCallback(returned -> {
            String msg = String.format("消息[%s]被退回，指定的交换器[%s]与路由键[%s]上没有绑定的队列",
                    new String(returned.getMessage().getBody()), returned.getExchange(), returned.getRoutingKey());
            System.out.println(msg);
//            System.out.println("ReturnsCallback: 消息:" + returned.getMessage());
//            System.out.println("ReturnsCallback: 回应码:" + returned.getReplyCode());
//            System.out.println("ReturnsCallback: 回应信息:" + returned.getReplyText());
//            System.out.println("ReturnsCallback: 交换机:" + returned.getExchange());
//            System.out.println("ReturnsCallback: 路由键:" + returned.getRoutingKey());
        });
        return rabbitTemplate;
    }
}
